Meteor.publish("orders", function () {
  if (this.userId) {
    if (Roles.userIsInRole(this.userId, 'driver')) {
      return Orders.find({
        'driverId': this.userId
      },
      {
        limit: 5,
        sort: {acceptTime: -1},
      });
    } else {
      return Orders.find({
        'userId': this.userId
      },
      {
        limit: 5,
      });
    }
  }
});


Meteor.publish("myOrders", function () {
  if (this.userId) {
    if (!Roles.userIsInRole(this.userId, 'driver')) {
      return Orders.find({ 'state': 'accept', 'userId': this.userId});
    }
  }
});

/*司机当前订单*/
Meteor.publish("currentOrder", function () {
  if (this.userId) {
    if (Roles.userIsInRole(this.userId, 'driver')) {
      return Orders.find({ 'state': {$ne: 'complete'}, 'driverId': this.userId});
    }
    else
      return Orders.find({ 'state': {$ne: 'complete'}, 'userId': this.userId});	
  }
});


Meteor.methods({
  startService: function (orderId) {
    //设置订单，开始工作
    Orders.upsert(orderId, {
      $set: {
        'startTime': new Date(),//开始时间
        'state': 'started',//状态
        'path': [],//行驶路径，
      }
    });
  },
  completeService: function (orderId) {
    //设置订单，开始工作
    console.log('orderId', orderId);
    Orders.upsert(orderId, {
      $set: {
        'endTime': new Date(),//结束时间
        'state': 'complete',//状态
      }
    });
  },
  pushPosition: function (lat, lng) {
    //如果是工作状态，将地址存入订单集合的path属性中，以便结算。
    //var workstate = Meteor.user().workstate;
    //console.log('workstate = ', workstate);
    Orders.update(
      {
        'driverId': this.userId,
        'state': 'started',
      },
      {
        $push: {'path': { lat: lat, lng: lng } }
      }
    );
  },

  setPathLength: function (orderId, length) {

    Orders.upsert(
      {
        '_id': orderId,        
      },
      {
        $set: {'pathLength': length}
      }
    );
  },
});
